package com.mo.lib.utils

import android.content.SharedPreferences
import android.os.Parcelable
import com.dylanc.longan.application
import com.tencent.mmkv.MMKV

/**
 * @ author：mo
 * @ data：2020/10/27:18:06
 * @ 功能：
 */
object MmkvUtils {
    /**初始化 */
    fun initMmkv() {
        MMKV.initialize(application)
    }

    val def: MMKV? = MMKV.defaultMMKV()

    /** 导入spf*/
    fun importSpf(old_man: SharedPreferences) {
        def?.importFromSharedPreferences(old_man)
        //    old_man.edit().clear().commit();
    }

    /**移除某个key对 */
    fun removeKey(key: String) {
        def?.removeValueForKey(key)
    }

    /** 清除所有key*/
    fun clearAll() {
        def?.clearAll()
    }

    /** 保存数据,根据默认值的类型调用不同的保存方法*/
    fun encode(key: String, obj: Any) {
        when (obj) {
            is String -> def?.encode(key, obj)
            is Int -> def?.encode(key, obj)
            is Boolean -> def?.encode(key, obj)
            is Float -> def?.encode(key, obj)
            is Long -> def?.encode(key, obj)
            is Double -> def?.encode(key, obj)
            is ByteArray -> def?.encode(key, obj)
            else -> def?.encode(key, obj.toString())
        }
    }

    /**
     * 获取数据，根据默认值的类型调用不同的取值方法
     */
    fun <T>decode(key: String, obj: T): T {
        return when (obj) {
            is String -> def?.decodeString(key, obj) as T
            is Int -> def?.decodeInt(key, obj)as T
            is Boolean -> def?.decodeBool(key, obj)as T
            is Float -> def?.decodeFloat(key, obj)as T
            is Long -> def?.decodeLong(key, obj)as T
            is Double -> def?.decodeDouble(key, obj)as T
            is ByteArray -> def?.decodeBytes(key, obj)as T
            else -> def?.decodeString(key, obj.toString())as T
        }
    }

    /** 得到保存数据的方法，我们根据默认值得到保存的数据的具体类型，然后调用相对于的方法获取值*/
    fun decodeInt(key: String): Int {
        return decode(key, 0) as Int
    }

    fun decodeDouble(key: String): Double {
        return decode(key, 0.00) as Double
    }

    fun decodeLong(key: String): Long {
        return decode(key, 0L) as Long
    }

    fun decodeBoolean(key: String): Boolean {
        return decode(key, false) as Boolean
    }

    fun decodeFloat(key: String): Float {
        return decode(key, 0f) as Float
    }

    fun decodeBytes(key: String): ByteArray {
        return decode(key, ByteArray(0)) as ByteArray
    }

    fun decodeString(key: String): String {
        return decode(key, "") as String
    }

    fun decodeStringSet(key: String?): Set<String>? {
        return def?.decodeStringSet(key, emptySet())
    }

    fun decodeParcelable(key: String?): Parcelable? {
        return def?.decodeParcelable(key, null)
    }

    fun encodeSet(key: String?, sets: Set<String?>?) {
        def?.encode(key, sets)
    }

    fun encodeParcelable(key: String?, obj: Parcelable?) {
        def?.encode(key, obj)
    }
}